<!--
 * @Description: ***
 * @Author: 丁飞洋
 * @Date: 2025-07-31 14:20:52
 * @LastEditTime: 2025-11-14 23:04:11
 * @LastEditors: 丁飞洋
-->
<template>
  <ResizableSplitLayout>
    <template #left>
      <div class="content">
        <!-- <riskAxis></riskAxis> -->
        <div class="table-container">
          <a-table 
            :data-source="tableData" 
            :columns="columns" 
            size="small" 
            :pagination="false"
            :loading="loading"
            :customRow="customRow"
          >
            <template #bodyCell="{ column, record, index }">
              <template v-if="column.dataIndex === 'name'">
                <div class="drag-handle-container">
                  <span class="drag-handle" 
                    draggable="true"
                    @dragstart="(e) => handlePersonInfoDragStart(e, record)"
                    title="拖拽创建人员信息节点"
                  >👤</span>
                  <span class="drag-handle" 
                    draggable="true"
                    @dragstart="(e) => handleTextDragStart(e, record)"
                    title="拖拽创建文本节点"
                  >📝</span>
                  <span class="drag-handle" 
                    draggable="true"
                    @dragstart="(e) => handleTableDragStart(e, record)"
                    title="拖拽创建表格节点"
                  >📊</span>
                  <span class="drag-handle" 
                    draggable="true"
                    @dragstart="(e) => handlePersonTrajectoryDragStart(e, record)"
                    title="拖拽创建人像轨迹节点"
                  >🖼️</span>
                  <span class="name-text">{{ record.name }}</span>
                </div>
              </template>
            </template>
          </a-table>
        </div>
      </div>
    </template>
    <template #right>
      <DeepThinking ref="deepThinkingRef" />
      <!-- <div class="content" style="background-color: #409eff"> -->
      <!-- <a-button type="primary" @click="showModal">按钮1</a-button> -->
      <!-- <abnormal zjhm="410211199805080018"></abnormal> -->
      <!-- <assess ref="modalAssessRef" zjhm="410211199805080018" @ok="onOk" @cancel="onCancel"></assess> -->
      <!-- <assessTemplate ></assessTemplate> -->
      <!-- 娱乐场所从业 -->
      <!-- <YLNode /> -->
      <!-- 参保信息 -->
      <!-- <CBNode /> -->
      <!-- 人像轨迹 -->
      <!-- <PersonTrajectory /> -->
      <!-- </div> -->
    </template>
  </ResizableSplitLayout>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { message } from "ant-design-vue";
import ResizableSplitLayout from "@/components/ResizableSplitLayout/index.vue";
import riskAxis from "./text/riskAxis.vue";
import DeepThinking from "./DeepThinking.vue";
// import PersonTrajectory from "./PersonTrajectory.vue";
// import YLNode from "./YLNode.vue";
// import CBNode from "./CBNode.vue";
// import abnormal from "@/components/abnormal/index.vue"
// import assess from "@/components/assess/index.vue"
// import assessTemplate from "@/components/assess/assessTemplate.vue"

const list = ref(["测试1", "测试2", "测试3", "测试4", "测试5", "测试6"]);
const text = ref(
  "根据您遇到的错误信息和之前的对话历史，这个错误表明在Promise异步操作中尝试访问了一个未定义对象的getYCZSList方法。结合您之前询问的Vue3组件通信和弹窗组件实现，我将详细分析可能的原因和解决方案。"
);
const modalAssessRef = ref();
const deepThinkingRef = ref<any>(null);

// 加载状态
const loading = ref(false);

// 表格列定义
const columns = ref([
  {
    title: "序号",
    dataIndex: "index",
    width: 60,
    customRender: ({ index }: any) => {
      return index + 1;
    },
  },
  {
    title: "姓名",
    dataIndex: "name",
    ellipsis: true,
    width: "auto",
  },
  {
    title: "证件号码",
    dataIndex: "idCard",
    ellipsis: true,
    width: "auto",
  },
  {
    title: "状态",
    dataIndex: "status",
    width: 100,
    customRender: ({ text }: any) => {
      if (text == '1') {
        return '正常';
      } else if (text == '2') {
        return '异常';
      } else if (text == '0') {
        return '待处理';
      } else {
        return '未知';
      }
    },
  },
  {
    title: "创建时间",
    dataIndex: "createTime",
    width: "auto",
  },
]);

// 表格数据
const tableData = ref<any[]>([]);

// 自定义行属性，使整行可拖拽
const customRow = (record: any, index: number) => {
  return {
    draggable: true,
    onDragStart: (e: DragEvent) => {
      // 检查是否选中了人员信息节点，并获取节点ID
      const sourceNodeId = checkPersonInfoNodeSelected();
      if (!sourceNodeId) {
        e.preventDefault();
        return;
      }
      // 默认拖拽行为：创建人员信息节点
      handlePersonInfoDragStart(e, record);
    },
    style: {
      cursor: 'move'
    }
  };
};

// 检查是否选中了人员信息节点，并返回节点ID
const checkPersonInfoNodeSelected = (): string | null => {
  if (!deepThinkingRef.value) {
    message.warning('请先选择画布中的人员信息节点');
    return null;
  }
  
  const selectedNode = deepThinkingRef.value.getSelectedNode();
  if (!selectedNode) {
    message.warning('请先选择画布中的人员信息节点');
    return null;
  }
  
  if (selectedNode.type !== 'person-info') {
    message.warning('只能从人员信息节点拖拽创建子节点，请先选择人员信息节点');
    return null;
  }
  
  return selectedNode.id;
};

// 拖拽创建人员信息节点
const handlePersonInfoDragStart = (event: DragEvent, record: any) => {
  event.stopPropagation(); // 阻止事件冒泡，避免触发行的默认拖拽
  
  // 检查是否选中了人员信息节点，并获取节点ID
  const sourceNodeId = checkPersonInfoNodeSelected();
  if (!sourceNodeId) {
    event.preventDefault();
    return;
  }
  
  const nodeData = {
    avatar: '',
    idNumber: record.idCard,
    idCard: record.idCard,
    width: 200,
    height: 150
  };
  
  event.dataTransfer!.setData('application/node-type', 'person-info');
  event.dataTransfer!.setData('application/node-data', JSON.stringify(nodeData));
  event.dataTransfer!.setData('source-node-id', sourceNodeId); // 设置源节点ID，用于创建连线
  event.dataTransfer!.effectAllowed = 'copy';
  
  console.log('拖拽创建人员信息节点:', record, '源节点ID:', sourceNodeId);
};

// 拖拽创建文本节点
const handleTextDragStart = (event: DragEvent, record: any) => {
  event.stopPropagation();
  
  // 检查是否选中了人员信息节点，并获取节点ID
  const sourceNodeId = checkPersonInfoNodeSelected();
  if (!sourceNodeId) {
    event.preventDefault();
    return;
  }
  
  const nodeData = {
    title: `${record.name} - 信息`,
    text: `姓名：${record.name}\n证件号码：${record.idCard}\n状态：${record.status === '1' ? '正常' : record.status === '2' ? '异常' : '待处理'}\n创建时间：${record.createTime}`,
    content: `姓名：${record.name}\n证件号码：${record.idCard}\n状态：${record.status === '1' ? '正常' : record.status === '2' ? '异常' : '待处理'}\n创建时间：${record.createTime}`,
    width: 300,
    height: 150
  };
  
  event.dataTransfer!.setData('application/node-type', 'text');
  event.dataTransfer!.setData('application/node-data', JSON.stringify(nodeData));
  event.dataTransfer!.setData('source-node-id', sourceNodeId); // 设置源节点ID，用于创建连线
  event.dataTransfer!.effectAllowed = 'copy';
  
  console.log('拖拽创建文本节点:', record, '源节点ID:', sourceNodeId);
};

// 拖拽创建表格节点
const handleTableDragStart = (event: DragEvent, record: any) => {
  event.stopPropagation();
  
  // 检查是否选中了人员信息节点，并获取节点ID
  const sourceNodeId = checkPersonInfoNodeSelected();
  if (!sourceNodeId) {
    event.preventDefault();
    return;
  }
  
  const nodeData = {
    title: `${record.name} - 详细信息`,
    columns: [
      { prop: 'name', label: '姓名', width: 100 },
      { prop: 'idCard', label: '证件号码', minWidth: 150 },
      { prop: 'status', label: '状态', width: 100 },
      { prop: 'createTime', label: '创建时间', minWidth: 150 }
    ],
    data: [
      {
        name: record.name,
        idCard: record.idCard,
        status: record.status === '1' ? '正常' : record.status === '2' ? '异常' : '待处理',
        createTime: record.createTime
      }
    ],
    width: 600,
    height: 300
  };
  
  event.dataTransfer!.setData('application/node-type', 'table');
  event.dataTransfer!.setData('application/node-data', JSON.stringify(nodeData));
  event.dataTransfer!.setData('source-node-id', sourceNodeId); // 设置源节点ID，用于创建连线
  event.dataTransfer!.effectAllowed = 'copy';
  
  console.log('拖拽创建表格节点:', record, '源节点ID:', sourceNodeId);
};

// 拖拽创建人像轨迹节点
const handlePersonTrajectoryDragStart = (event: DragEvent, record: any) => {
  event.stopPropagation();
  
  // 检查是否选中了人员信息节点，并获取节点ID
  const sourceNodeId = checkPersonInfoNodeSelected();
  if (!sourceNodeId) {
    event.preventDefault();
    return;
  }
  
  const nodeData = {
    title: `${record.name} - 人像轨迹`,
    data: [
      {
        photo: '',
        idNumber: record.idCard,
        idCard: record.idCard,
        gmsfzhm: record.idCard,
        time: record.createTime,
        shot_time: record.createTime,
        location: '未知地点',
        sb_mc: '未知地点',
        address: '未知地点'
      }
    ],
    itemsPerPage: 10,
    width: 850,
    height: 500
  };
  
  event.dataTransfer!.setData('application/node-type', 'person-trajectory');
  event.dataTransfer!.setData('application/node-data', JSON.stringify(nodeData));
  event.dataTransfer!.setData('source-node-id', sourceNodeId); // 设置源节点ID，用于创建连线
  event.dataTransfer!.effectAllowed = 'copy';
  
  console.log('拖拽创建人像轨迹节点:', record, '源节点ID:', sourceNodeId);
};

// 生成模拟数据
const generateMockData = () => {
  const names = [
    "张三", "李四", "王五", "赵六", "钱七", 
    "孙八", "周九", "吴十", "郑一", "王二"
  ];
  const statuses = ['0', '1', '2'];
  
  const mockData = [];
  for (let i = 0; i < 10; i++) {
    const date = new Date();
    date.setDate(date.getDate() - Math.floor(Math.random() * 30));
    
    mockData.push({
      key: i + 1,
      name: names[i] || `用户${i + 1}`,
      idCard: `11010119${String(Math.floor(Math.random() * 100000000)).padStart(8, '0')}${String(Math.floor(Math.random() * 100)).padStart(2, '0')}`,
      status: statuses[Math.floor(Math.random() * statuses.length)],
      createTime: date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      }).replace(/\//g, '-'),
    });
  }
  return mockData;
};

// 初始化数据
onMounted(() => {
  loading.value = true;
  setTimeout(() => {
    tableData.value = generateMockData();
    loading.value = false;
  }, 300);
});

// 打开研判弹窗
const showModal = () => {
  modalAssessRef.value.open = true;
};
// 研判提交
const onOk = () => {
  console.log("OK clicked");
};
// 研判取消
const onCancel = () => {
  console.log("Cancel clicked");
};
</script>

<style scoped>
.content {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.table-container {
  flex: 1;
  overflow: auto;
  margin-top: 20px;
}

.drag-handle-container {
  display: flex;
  align-items: center;
  gap: 4px;
}

.drag-handle {
  cursor: move;
  font-size: 14px;
  padding: 2px 4px;
  border-radius: 4px;
  transition: background-color 0.2s;
  user-select: none;
}

.drag-handle:hover {
  background-color: #f0f0f0;
}

.drag-handle:active {
  background-color: #d9d9d9;
}

.name-text {
  margin-left: 4px;
}
</style>
